import java.util.LinkedList;
import java.util.Queue;

import org.junit.Assert;
import org.junit.Test;

public class MyStack {

	Queue<Integer> queue1 = new LinkedList<>();
	Queue<Integer> queue2 = new LinkedList<>();

	// Push element x onto stack.
	public void push(int x) {
		if (queue1.isEmpty() && queue2.isEmpty()) {
			queue1.add(x);
		} else if (!queue1.isEmpty()) {
			queue1.add(x);
		} else if (!queue2.isEmpty()) {
			queue2.add(x);
		}
	}

	// Removes the element on top of the stack.
	public void pop() {
		if (queue1.isEmpty() && queue2.isEmpty()) {
			return;
		} else if (queue1.isEmpty()) {
			while (!queue2.isEmpty() && queue2.size() > 1) {
				queue1.add(queue2.poll());
			}
			queue2.poll();
		} else if (queue2.isEmpty()) {
			while (!queue1.isEmpty() && queue1.size() > 1) {
				queue2.add(queue1.poll());
			}
			queue1.poll();
		}
	}

	// Get the top element.
	public int top() {
		int value;
		if (queue1.isEmpty() && queue2.isEmpty()) {
			return 0;
		} else if (queue1.isEmpty()) {
			while (!queue2.isEmpty() && queue2.size() > 1) {
				queue1.add(queue2.poll());
			}
			value = queue2.poll();
			queue1.add(value);
		} else if (queue2.isEmpty()) {
			while (!queue1.isEmpty() && queue1.size() > 1) {
				queue2.add(queue1.poll());
			}
			value = queue1.poll();
			queue2.add(value);
		} else {
			value = 0;
		}
		return value;
	}

	// Return whether the stack is empty.
	public boolean empty() {
		return queue1.isEmpty() && queue2.isEmpty();
	}

	@Test
	public void test() {
		MyStack stack = new MyStack();
		Assert.assertTrue(stack.empty());
		stack.push(1);
		stack.push(2);
		stack.push(3);
		Assert.assertEquals(3, stack.top());
		stack.pop();
		stack.pop();
		Assert.assertEquals(1, stack.top());
		stack.push(4);
		Assert.assertEquals(4, stack.top());
		stack.pop();
		stack.pop();
		Assert.assertTrue(stack.empty());
	}

}
